// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.moc.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ImportResp;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ModifyTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.MocDetailDao;
import com.liuxinlong.modules.dao.MocRecordDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.MocDetail;
import com.liuxinlong.modules.entity.MocRecord;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.material.dto.MaterialStatusImportDto;
import com.liuxinlong.modules.material.service.MaterialStatusService;
import com.liuxinlong.modules.moc.dto.ImportMocDataDto;
import com.liuxinlong.modules.moc.service.MocDetailService;
import com.liuxinlong.modules.moc.service.MocRecordService;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物料变更记录服务层接口实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022-01-18
 */
@Service
@Slf4j
public class MocRecordServiceImpl implements MocRecordService {

    @Autowired
    private MocRecordDao mocRecordDao;

    @Autowired
    private MocDetailDao mocDetailDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private MaterialStatusService materialStatusService;

    @Autowired
    private MocDetailService mocDetailService;

    @Autowired
    private FileManageDao fileManageDao;

    @Override
    public List<Map<String, Object>> pageRecordInfo(Map<String, Object> queryParam) {
        List<String> idList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(queryParam.get("keyword"))) {
            List<MocDetail> mocDetails = mocDetailDao.pageDetailList(queryParam);
            idList = mocDetails.stream().map(MocDetail::getRecordId).collect(Collectors.toList());
        }
        queryParam.put("idList", idList);
        List<MocRecord> originList = mocRecordDao.pageRecordList(queryParam);
        List<Map<String, Object>> resultList = completeResult(originList, (int) queryParam.get("startNum"));
        return resultList;
    }

    @Override
    public int getRecordCount(Map<String, Object> queryParam) {
        return mocRecordDao.getRecordCount(queryParam);
    }

    @Override
    public void addRecordInfo(MocRecord mocRecord) {
        String id = SnowFlake.nextIdStr();
        mocRecord.setId(id);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        mocRecord.setEnterUser(currentUser.getId());
        String attach = mocRecord.getAttach();
        if (StringUtils.isNotEmpty(attach)) {
            fileManageService.updateBusinessFile(attach, id);
        }
        mocRecordDao.insert(mocRecord);

    }

    @Override
    public void updateRecordInfo(MocRecord mocRecord) {
        String attach = mocRecord.getAttach();
        fileManageService.updateBusinessFile(attach, mocRecord.getId());
        mocRecordDao.updateById(mocRecord);

    }

    @Override
    @Transactional
    public void deleteRecordInfo(String id) {
        MocRecord mocRecord = mocRecordDao.selectById(id);
        if (ObjectUtils.isEmpty(mocRecord)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR,"删除失败，修改记录不存在！");
        }
        Map<String,Object> queryDetailParam = new HashMap<>();
        queryDetailParam.put("recordId",id);
        queryDetailParam.put("startNum",0);
        queryDetailParam.put("pageSize",10000);
        List<MocDetail> detailList = mocDetailDao.pageDetailList(queryDetailParam);
        if (mocRecord.getChangeType() == 3) {

        }
        if (mocRecord.getChangeType() == 2) {

        }

        mocRecordDao.deleteById(id);

    }

    @Override
    public ImportResp importData(String fileName, int mocType, String approve, String remark) {
        String id = SnowFlake.nextIdStr();
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        ImportResp resp = new ImportResp();

        MocRecord mocRecord = new MocRecord();
        mocRecord.setId(id);
        mocRecord.setReason(remark);
        FileManage fileManage = fileManageDao.selectById(fileName);
        if (mocType == 2) {
            mocRecord.setTitle("物料参数变更 " + TimeUtils.getDate(TimeFormatConstants.YYYYMMDD));
            resp = mocDetailService.importDetails(fileManage.getFilePath());
        } else if (mocType == 3) {
            mocRecord.setTitle("物料状态变更 " + TimeUtils.getDate(TimeFormatConstants.YYYYMMDD));
            resp = materialStatusService.importDetails(fileManage.getFilePath());
        } else {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "不支持当前操作！");
        }
        resp.setId(id);
        mocRecord.setChangeType(mocType);
        String attach = fileName + "," + approve;
        mocRecord.setAttach(attach);
        mocRecord.setChangeTime(currentTime);
        mocRecord.setOperateTime(currentTime);
        mocRecord.setEnterUser(currentUser.getId());
        mocRecordDao.insert(mocRecord);
        fileManageService.updateBusinessFile(attach, id);
        return resp;
    }

    @Override
    public ImportResp batchAddData(List<ImportMocDataDto> dataList, String recordId) {
        MocRecord mocRecord = mocRecordDao.selectById(recordId);
        if (ObjectUtils.isEmpty(mocRecord)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "变更记录不存在！");
        }
        ImportResp resp = new ImportResp();
        if (mocRecord.getChangeType() == 2) {
            List<MocDetail> detailList = new ArrayList<>(dataList.size());
            for (ImportMocDataDto dto : dataList) {
                MocDetail detail = new MocDetail();
                detail.setMaterial(dto.getMaterial());
                detail.setRegion(dto.getRegion());
                detail.setDescription(dto.getDescription());
                detail.setParam(dto.getParam());
                detail.setOldValue(dto.getOldValue());
                detail.setNewValue(dto.getNewValue());
                detail.setRemark(dto.getRemark());
                detailList.add(detail);
            }
            resp = mocDetailService.batchAddDetail(detailList, recordId);
        } else if (mocRecord.getChangeType() == 3) {
            List<MaterialStatusImportDto> statusList = new ArrayList<>(dataList.size());
            for (ImportMocDataDto dto : dataList) {
                MaterialStatusImportDto detail = new MaterialStatusImportDto();
                detail.setMaterial(dto.getMaterial());
                detail.setRegionOne(dto.getRegionOne());
                detail.setRegionTwo(dto.getRegionTwo());
                detail.setRegionThree(dto.getRegionThree());
                detail.setChangeTime(dto.getChangeTime());
                statusList.add(detail);
            }
            resp = materialStatusService.batchAddDetail(statusList, recordId);
        } else {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "不支持当前操作！");
        }
        resp.setId(recordId);
        return resp;
    }

    /**
     * 数据填充
     *
     * @param originList 初始数据列表
     * @param startNum   查询起始值
     * @return 完整数据
     */
    private List<Map<String, Object>> completeResult(List<MocRecord> originList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        int sort = startNum + 1;
        for (MocRecord record : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(record);
            map.put("sort", sort);
            map.put("changeTypeName", ModifyTypeEnum.getNameByValue(record.getChangeType()));
            if (StringUtils.isNotEmpty(record.getEnterUser()) && userMap.containsKey(record.getEnterUser())) {
                map.put("enterUserName", userMap.get(record.getEnterUser()).get("name"));
            }
            resultList.add(map);
            sort++;
        }
        return resultList;

    }
}
